<template>
  <div ref="chart" style="width: 100%; height: 300px;"></div>
</template>

<script setup lang="ts">
import { ref, onMounted, onBeforeUnmount, defineProps, watch } from 'vue';
import * as echarts from 'echarts';

// 接收 props
const props = defineProps<{
  data: { farmHouseName: string; waterConsumption: number; }[]; // 接收的数据格式
}>();

const chart = ref(null);
const myChart = ref(null);

const setChartOption = () => {
  const xAxisData = props.data.map(item => item.farmHouseName);
  const seriesData = props.data.map(item => item.waterConsumption);

  const option = {
    title: {
      text: "耗水",
    },
    grid: {
      left: "2%",
      right: "2%",
      bottom: "5%",
      top: 50,
      containLabel: true
    },
    tooltip: {
      trigger: "item",
      axisPointer: {
        type: "cross",
      },
    },
    legend: {
      data: ["耗水"],
    },
    xAxis: [
      {
        type: 'category',
        data: xAxisData,
        axisTick: true,
        axisLine: {
          show: true,
        },
        axisLabel: {
          show: true,
          color: "#6DB7FF",
          fontSize: 16
        },
      },
    ],
    yAxis: [
      {
        min: 0,
        type: 'value',
        axisLine: {
          show: true,
        },
        splitLine: {
          show: false,
        },
        axisLabel: {
          show: true,
          color: "#6DB7FF",
          fontSize: 16
        },
      }
    ],
    series: [
      {
        name: "耗水",
        type: 'bar',
        barWidth: 18,
        data: seriesData,
        itemStyle: {
          opacity: 0.8,
          color: {
            type: 'linear',
            x: 0,
            y: 0,
            x2: 0,
            y2: 1,
            colorStops: [{
                offset: 0,
                color: '#00F0FF'
            }, {
                offset: 1,
                color: '#0066FF'
            }]
          },
          barBorderRadius: [8, 8, 0, 0],
        },
      },
    ],
  };
  if (myChart.value) {
    myChart.value.setOption(option);
  }
};

onMounted(() => {
  myChart.value = echarts.init(chart.value);
  setChartOption();

  window.addEventListener('resize', () => {
    myChart.value.resize();
  });
});

// 监听数据变化
watch(() => props.data, setChartOption, { immediate: true });

onBeforeUnmount(() => {
  window.removeEventListener('resize', () => {
    myChart.value.resize();
  });
  if (myChart.value) {
    myChart.value.dispose();
  }
});
</script>

<style scoped>
/* 添加一些样式 */
</style>
